﻿namespace GoodAdmin.CodeGenerator;

public class DbService : IDbService, ITransient
{
    private readonly ISqlSugarClient db;

    public DbService(ISqlSugarClient db)
    {
        this.db = db;
    }

    /// <inheritdoc/>
    public Task CreateTable()
    {
        throw new NotImplementedException();
    }
    /// <inheritdoc/>
    public List<DbConfigOutput> GetDbConfig()
    {
        var configs=App.GetOptions<DbConnectionOptions>().ConnectionConfigs;
        return configs.Adapt<List<DbConfigOutput>>();
    }
    /// <inheritdoc/>
    public List<DbTableInfo> GetTables(string ConfigId)
    {
        var dbProvider = db.AsTenant().GetConnectionScope(ConfigId);
        if (dbProvider == null) return new List<DbTableInfo>();
        List<DbTableInfo>? tables = dbProvider.DbMaintenance.GetTableInfoList();
        //只取table
        tables = tables.Where(it => it.DbObjectType == DbObjectType.Table).ToList();
        return tables;
    }
    /// <inheritdoc/>
    public List<TableFileds> GetTableField(string ConfigId, string TableNames)
    {
        if (string.IsNullOrWhiteSpace(ConfigId))
        {
            throw Oops.Bah(CodeGenErrorCode.CG003);
        }
        if (string.IsNullOrWhiteSpace(TableNames))
        {
            throw Oops.Bah(CodeGenErrorCode.CG004);
        }
        var dbProvider = db.AsTenant().GetConnectionScope(ConfigId);
        List<TableFileds> list = new();
        var tableList=TableNames.Split(',');
        foreach(string tableName in tableList)
        {
            List<DbColumnInfo> dbColumnInfos = dbProvider.DbMaintenance.GetColumnInfosByTableName(tableName);
            var fieldInfo = dbColumnInfos.Adapt<List<FieldInfo>>();
            list.Add(new TableFileds { TableName = tableName, FieldInfos = fieldInfo });
        }
        return list;
    }
}